Vue.component('yl-table', {
    template: `<div>
    <el-row :gutter="10">
        <el-col :span="span" v-for="i in count" :key="i">
            <el-table :data="data.slice((page-1+(i-1))*limit,(page+(i-1))*limit)" height="530px" stripe border style="width: 100%">
                <el-table-column fixed="left" prop="1" align="center" label="序号" width="50">
                    <template v-slot="{row,$index}">
                        {{$index + 1 + (i-1)*10}}
                    </template>
                </el-table-column>
                <slot></slot>
                <el-table-column fixed="right"  label="操作" align="center" width="80">
                    <template v-slot="{row,$index}">
                        <el-button v-if="row.Row_Status == '0'||row.Row_Status2=='9'" size="small" type="danger" @click="handleRemove($index,i)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>
    <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[10*num, 20*num, 30*num, 40*num]"
        :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="data.length">
    </el-pagination></div>`,
    props: {
        data: {
            type: Array,
            default: function () {
                return []
            }
        },
        num: {
            type: Number,
            default: 3
        }
    },
    data() {
        return {
            form: {
                page: 1,
                limit: this.num * 10
            }
        }
    },
    computed: {
        page() {
            return 1 + (this.form.page - 1) * this.num;
        },
        limit() {
            return this.form.limit / this.num;
        },
        span() {
            return 24 / this.count;
        },
        count() {
            if (this.data.length < this.form.limit) {
                let length = this.data.length == 0 ? 0 : this.data.length - 1
                let num = parseInt(length / this.limit) + 1
                return num;
            } else {
                return this.num;
            }
        }
    },
    methods: {
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleRemove(index, i) {
            let page = this.form.page;
            let limit = this.form.limit / this.num;
            let $i = (page - 1) * this.form.limit + (index + (i - 1) * limit);
            this.$emit('remove',$i);
        }
    },
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Activity_SerialNumber: '',
                Activity_Name: '',//供应商名称
                Activity_Notice: '',//所属地址
                Project_SerialNumber:'',
                Start_Date: '',
                End_Date: '',
                Date: null,
                Activity_Notes: '',
                Enterprise_Info_SerialNumber: '',
                Children: {
                    business_activity_article: [],
                    business_activity_member: []
                },

            },
            tableData: [],
            rules: {
                Page_SerialNumber: [{ required: true, message: '请选择活动页面', trigger: 'change' }],
                Date: [{ required: true, message: '请选择执行时间', trigger: 'blur' }]
            },
            project:[],
            department: [],
            business_department_info: [],
            article_specifications: [],
            dialogVisible: false,
            loading: false,
            page: [],
            defaultProps: {
                children: 'Children',
                label: 'Department_Name',
                value: 'Department_SerialNumber',
                checkStrictly: true,
                multiple: true
            },
            drawer: false,
            radio: '1',
            input1: '',
            input2: '',
            table:true,
        }
    },
    watch:{
        article_specifications(){
            this.table = false;
            const timer = setTimeout(() => {
                this.table = true;
                clearTimeout(timer)
            })
        },
        input1(val) {//根据毛利率设置平台价
            if (this.radio == '1') {
                this.article_specifications.filter(i=>i.Row_Status!='1').forEach(item => {
                    item.Activity_Unit_Price = accDiv(item.Purchase_Unit_Price, accSub(1, val / 100).toFixed(2)).toFixed(2);
                })
            }
        },
        input2(val) {
            if (this.radio == '2') {
                this.article_specifications.filter(i=>i.Row_Status!='1').forEach(item => {
                    item.Activity_Unit_Price = accMul(item.JDCOM_Unit_Price1, val / 100).toFixed(2);
                })
            }
        },
        radio(val) {
            if (val == '2') {
                this.input1 = '';
            } else {
                this.input2 = '';
            }
            this.article_specifications.filter(i=>i.Row_Status!='1').forEach(item => {
                item.Activity_Unit_Price = '';
            })
        }
    },
    mounted() {
        const Activity_SerialNumber = sessionStorage.getItem("Activity_SerialNumber")
        this.getData(Activity_SerialNumber);
    },
    methods: {
        getArticle(data) {
            //如果是新的，则添加，不是则不添加
            let arr = [... this.article_specifications,...data];
            arr.forEach(item=>{
                if (this.article_specifications.some(i=>i.Supplier_Article_SerialNumber==item.Supplier_Article_SerialNumber )) {
                    let obj = this.article_specifications.filter(i=>i.Supplier_Article_SerialNumber==item.Supplier_Article_SerialNumber )[0];
                    item.Activity_Unit_Price = obj.Activity_Unit_Price;
                }
            })
            this.article_specifications = arr;
        },
        getData(DocumentSerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'GET',
                data: {
                    Data: "base_page_info",
                    Condition: "Row_Status='0' and Absolute_Path<>''"
                },
                success: function (data) {
                    data.forEach((item, index) => {
                        item.is = index == 0 ? true : false;
                    })
                    that.page = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'GET',
                data: {
                    Data: "business_project",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.project = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllDepartmentByUserName?UserName=&ParentNumber=`,
                type: 'GET',
                success: function (data) {
                    that.department = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalGetDataStructure`,
                type: 'POST',
                data: {
                    DocumentSerialNumber,
                    Data: JSON.stringify({ business_activity: { business_activity_article: {}, business_activity_member: {} } }),
                    Condition: ""
                },
                success: function (data) {
                    if (data.business_activity.length > 0) {
                        data.business_activity[0].Date = [data.business_activity[0].Start_Date, data.business_activity[0].End_Date];
                        that.form = data.business_activity[0];
                        that.business_department_info = that.form.DepartmentJSON;
                        let str = "";//商品内码
                        //# that.form.Children.business_activity_article.filter(i => i.Row_Status != '1').forEach(item => {
                        // that.form.Children.business_activity_article.forEach(item => {
                        //     if (item.Supplier_Article_SerialNumber) {
                        //         if (str) {
                        //             str = str + " or business_supplier_article.Supplier_Article_SerialNumber = '" + item.Supplier_Article_SerialNumber + "'\r\n"
                        //         } else {
                        //             str = " business_supplier_article.Supplier_Article_SerialNumber = '" + item.Supplier_Article_SerialNumber + "'\r\n"
                        //         }
                        //     }
                        // })
                        that.form.Children.business_activity_article.forEach(item => {
                            if (str) {
                                str = str + " or business_activity_article.Activity_Article_SerialNumber = '" + item.Activity_Article_SerialNumber + "'\r\n"
                            } else {
                                str = " business_activity_article.Activity_Article_SerialNumber = '" + item.Activity_Article_SerialNumber + "'\r\n"
                            }
                        })
                        if (str) {
                            let sql = "and (" + str + ")";
                            $.ajax({
                                headers: requestHeaders(),
                                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                                type: 'POST',
                                data: {
                                    SQLSerialNumber: "A_business_activity_article_1",
                                    Condition: '',
                                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(sql))),
                                },
                                success: function (Result) {
                                    Result.forEach(item => {
                                        //# that.form.Children.business_activity_article.filter(i => i.Row_Status != '1' && i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)[0]。。。
                                        let obj = that.form.Children.business_activity_article.filter(i => i.Activity_Article_SerialNumber == item.Activity_Article_SerialNumber)[0];
                                        item.Activity_Unit_Price = obj.Activity_Unit_Price
                                        item.Row_Status = obj.Row_Status
                                    })
                                    console.log(Result);
                                    that.article_specifications = Result;
                                },
                                complete: function (XMLHttpRequest) {
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            });
                        }

                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;

                    console.log(that.form.Children.business_activity_article.filter(i=>i.Row_Status == '0'));
                    console.log(that.article_specifications);
                    //筛出删除的商品
                    that.form.Children.business_activity_article.filter(i=>i.Row_Status == '0').forEach(item => {
                        if (!that.article_specifications.filter(i=>i.Row_Status != '1').some(i => i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)) {
                            item.Row_Status = '1';
                        }
                    })

                    //筛出恢复删除的商品
                    that.article_specifications.filter(i=>i.Row_Status != '1').forEach(item => {
                        if (that.form.Children.business_activity_article.filter(i=>i.Row_Status == '0').some(i => item.Supplier_Article_SerialNumber == i.Supplier_Article_SerialNumber)) {
                            let obj = that.form.Children.business_activity_article.filter(i =>i.Row_Status == '0' && item.Supplier_Article_SerialNumber == i.Supplier_Article_SerialNumber)[0];
                            obj.Activity_Unit_Price = item.Activity_Unit_Price;
                        }
                    })

                    //更新商品
                    that.article_specifications.filter(i=>i.Row_Status != '1').forEach(item => {
                        if (!that.form.Children.business_activity_article.filter(i=>i.Row_Status == '0').some(i => i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)) {
                            that.form.Children.business_activity_article.push({
                                Activity_Member_SerialNumber: '',
                                Activity_SerialNumber: that.form.Activity_SerialNumber,
                                Create_Datetime:getYMDHMSDate(),
                                ...item
                            })
                        }
                    })

                    that.form.Start_Date = that.form.Date[0];
                    that.form.End_Date = that.form.Date[1];

                    //筛出删除的部门
                    that.form.Children.business_activity_member.forEach(item => {
                        if (!that.business_department_info.some(i => i[i.length - 1] == item.Department_SerialNumber)) {
                            item.Row_Status = '1';
                        }
                    })
                    //筛出恢复删除的部门
                    that.business_department_info.forEach(item => {
                        if (that.form.Children.business_activity_member.some(i => item[item.length - 1] == i.Department_SerialNumber)) {
                            that.form.Children.business_activity_member.filter(i => item[item.length - 1] == i.Department_SerialNumber)[0].Row_Status = '0'
                        }
                    })
                    //更新新部门
                    that.form.DepartmentJSON = JSON.stringify(that.business_department_info);
                    that.business_department_info.forEach(item => {
                        if (!that.form.Children.business_activity_member.some(i => i.Department_SerialNumber == item[item.length - 1])) {
                            that.form.Children.business_activity_member.push({
                                Activity_Member_SerialNumber: '',
                                Activity_SerialNumber: that.form.Activity_SerialNumber,
                                Department_SerialNumber: item[item.length - 1]
                            })
                        }
                    })
                    const { add, modify } = that.deal()
                    let data = {}
                    if (add == null) {
                        data = { Data: JSON.stringify({ 
                            Modify: { business_activity: [modify] },
                            Add:{ 
                                base_operation_log:[generateLog('修改活动--'+that.form.Activity_Name, '平台端操作', 'business_activity', JSON.stringify({ Modify: { business_activity: [modify] } }))] } }) 
                            }
                    } else {
                        data = {
                            Data: JSON.stringify({ 
                                Modify: { business_activity: [modify] }, 
                                Add: { 
                                    business_activity: [add], 
                                    base_operation_log:[generateLog('修改活动--'+that.form.Activity_Name, '平台端操作', 'business_activity', JSON.stringify({ Modify: { business_activity: [modify] },Add:{business_activity: [add]} }))]  
                                } 
                            }),
                        }
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data,
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("提交成功")
                                window.location.href = './index.html';
                            } else {
                                that.$message.error("提交失败，请稍后再试")
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false;
                            requestPretreatment(XMLHttpRequest);//config/config.js 响应预检
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        deal() {
            const add = deepClone(this.form)
            const modify = deepClone(this.form)

            let add_business_activity_article = [], modify_business_activity_article = [];
            let add_business_activity_member = [], modify_business_activity_member = [];
            for (const i in modify.Children.business_activity_article) {
                const obj = modify.Children.business_activity_article[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_activity_article.push(obj)
                } else {
                    modify_business_activity_article.push(obj)
                }
            }
            for (const i in modify.Children.business_activity_member) {
                const obj = modify.Children.business_activity_member[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_activity_member.push(obj)
                } else {
                    modify_business_activity_member.push(obj)
                }
            }

            add.Children.business_activity_article = add_business_activity_article;
            modify.Children.business_activity_article = modify_business_activity_article;

            add.Children.business_activity_member = add_business_activity_member;
            modify.Children.business_activity_member = modify_business_activity_member;

            if (add_business_activity_article.length == 0 && add_business_activity_member.length == 0) {
                return { add: null, modify };
            }

            return { add, modify };
        },
        handleRemove($i) {
            this.article_specifications = this.article_specifications.filter((i, id) => id != $i)
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
})